﻿#region Copyright

// The contents of this file are subject to the Mozilla Public License
//  Version 1.1 (the "License"); you may not use this file except in compliance
//  with the License. You may obtain a copy of the License at
//  
//  http://www.mozilla.org/MPL/
//  
//  Software distributed under the License is distributed on an "AS IS"
//  basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
//  License for the specific language governing rights and limitations under 
//  the License.
//  
//  The Initial Developer of the Original Code is Robert Smyth.
//  Portions created by Robert Smyth are Copyright (C) 2008.
//  
//  All Rights Reserved.

#endregion

using NUnitGrid.Framework.Logging;
using NUnitGrid.GridClient.Plugins.GridClient.NUnitTestsFinder;
using NUnitGrid.Protocol.Commands;
using ProxyServer.Server;


namespace NUnitGrid.GridClient.Plugins.GridClient
{
    public class Client : IClient, IStartRunListener, IRunCompleteListener
    {
        private readonly IGridServerProxy gridServer;
        private readonly ILogger logger;
        private readonly IRunSessionListener runSessionListener;
        private readonly ITestsFinder testsFinder;
        private TestSession session;

        public Client(IGridServerProxy gridServer, ILogger logger, IRunSessionListener runSessionListener,
                      ITestsFinder testsFinder)
        {
            this.gridServer = gridServer;
            this.logger = logger;
            this.runSessionListener = runSessionListener;
            this.testsFinder = testsFinder;
        }

        public void OnStopAllTasks()
        {
            logger.Info.Write("Stop all tasks requested");
            runSessionListener.OnStopping();
            gridServer.StopAllGridTasks();
        }

        void IRunCompleteListener.OnCompleted(int passedCount, int failedCount)
        {
            session = null;
        }

        void IStartRunListener.OnRunRequest()
        {
            logger.Info.Write("Run requested");

            var fixtures = testsFinder.GetTests(ClientSettings.Default.TestAssembly);
            session = new TestSession(gridServer, runSessionListener, this, fixtures, logger);
            session.Start();
        }
    }
}